import random
from Tkinter import *
import tkMessageBox
import ConfigParser
import os
import tkSimpleDialog


class MyDialog(tkSimpleDialog.Dialog):

    def __init__(self, master, config):
        self._config = config
        tkSimpleDialog.Dialog.__init__(self, master)
        print 'it is sthis config %s' % self._config

    def body(self, master):

        Label(master, text="Percentage Cheating:").grid(row=0)
        self.e1 = Entry(master)
        self.e1.insert(0, str(self._config['cheating_percentage']))
        self.e1.grid(row=0, column=1)
        self._var = IntVar()
        self._var.set(self._config['cheating'])
        self.cb1 = Checkbutton(master, text="Cheating", variable=self._var)
        self.cb1.grid(row=1)
        return self.e1  # initial focus

    def apply(self):
        config = {}
        self._config['cheating_percentage'] = int(self.e1.get())
        self._config['cheating'] = self._var.get()
        print self._config


class Dice:
    _sides = 0

    def __init__(self, sides, loaded=False, cheating_percentage=100):
        self._sides = sides
        self._loaded = loaded
        self._cheating_percentage = cheating_percentage
        print self._cheating_percentage

    def _random_num_gen(self):
        roll = random.randint(1, int(self._sides))
        return roll

    def roll(self, amount_of_rolls):
        result = ""
        counted_values = 0
        done_rolls = 1
        cheating_rolls = float(amount_of_rolls) / 100 * self._cheating_percentage
        print 'Cheating rolls %s' % cheating_rolls
        print 'Amount of rolls %s' % amount_of_rolls
        while done_rolls <= int(amount_of_rolls):
            if self._loaded:
                roll = int(self._sides)
                result += "Dice %s rolls : %s %s" % (done_rolls, roll, '\n\r')
                done_rolls += 1
                if (done_rolls > cheating_rolls):
                    self._loaded = False
                counted_values += roll
                total_amount = "Total value : %s" % counted_values
                line_brake = len(total_amount) * "_"
            else:
                roll = self._random_num_gen()
                result += "Dice %s rolls : %s %s" % (done_rolls, roll, '\n\r')
                done_rolls += 1
                counted_values += roll
                total_amount = "Total value : %s" % counted_values
                line_brake = len(total_amount) * "_"
        result += "%s %s %s Total value : %s" % ('\n\r',
        line_brake, '\n\r', counted_values)
        return result


class Dicey:

    def __init__(self, master):
        #methods for writing and loading config
#        self._write_config()
        self._load_config()
        #master settings
        master.title("Dicey")
        self._master = master

        #labels
        Label(master, text="Amount of rolls : ").grid(row=0)
        Label(master, text="Amount of sides : ").grid(row=1)

        #entry fields
        self.amount_of_rolls = Entry(master, width=20)
        self.amount_of_rolls.grid(row=0, column=1, sticky=W)
        self.amount_of_sides = Entry(master, width=20)
        self.amount_of_sides.grid(row=1, column=1, sticky=W)

        #text field with scrollbar
        self.text_area_scrollbar = Scrollbar(master)
        self.text_area = Text(master, state="disabled",
        yscrollcommand=self.text_area_scrollbar.set,
        width=40)
        self.text_area.grid(row=2, column=1)
        self.text_area_scrollbar.grid(row=2, column=2, sticky=N + S + E + W)
        self.text_area_scrollbar.config(command=self.text_area.yview)

        #button
        Button(master, text="ROLL", command=self._roll_dice).grid(row=2,
        column=0)

        #menu
        ##main menu
        menu = Menu(master)
        master.config(menu=menu)
        ##filemenu
        filemenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New", command=self._callback)
        filemenu.add_command(label="Open...", command=self._callback)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=master.quit)
        ##edit menu
        editmenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="Edit", menu=editmenu)
        editmenu.add_command(label="Preferences",
         command=self._call_pref_dialog)
        ##helpmenu
        helpmenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About...", command=self._show_info)

    #methods
    def _callback(self):
        tkMessageBox.showwarning("To be implemented",
        "To be implemented")

    def _show_info(self):
        tkMessageBox.showinfo("Dicey info",
        "Version 1.0 \n\r Author Edwin Blommaerts")

    def _roll_dice(self):
        try:
            dice = Dice(self.amount_of_sides.get(), self._config['cheating'],
                                                 self._config['cheating_percentage'])
            result = dice.roll(int(self.amount_of_rolls.get()))
            self.text_area.config(state="normal")
            self.text_area.delete(1.0, END)
            self.text_area.insert(END, result)
            self.text_area.config(state="disabled")
        except ValueError:
            tkMessageBox.showwarning(
                "Bad input",
                "Illegal values, please try again"
            )
            return 0

    def _write_config(self):
        try:
            print self._config
            config = ConfigParser.RawConfigParser()
            config.add_section('Cheating')
            config.set('Cheating', 'cheating_percentage', int(self._config['cheating_percentage']))
            config.set('Cheating', 'cheating', str(self._config['cheating']))
            config_name = 'dicey_config.cfg'
            config_path = os.path.join(sys.path[0], config_name)
            with open(config_path, 'wb') as config_file:
                config.write(config_file)
            print 'Writing config : %s' % self._config
        except Exception, err:
            sys.stderr.write('ERROR: %s\n' % str(err))
            return 1

    def _load_config(self):
        try:
            defaults = {'cheat': False, 'cheating_percentage': 0}
            config = ConfigParser.SafeConfigParser(defaults)
            config_name = 'dicey_config.cfg'
            config_path = os.path.join(sys.path[0], config_name)
            config.read(config_path)
            self._config = {
            'cheating': config.getboolean('Cheating', 'cheating'),
            'cheating_percentage': config.getint('Cheating', 'cheating_percentage')
            }
            print 'Loading config %s' % self._config
        except Exception, err:
            sys.stderr.write('ERROR: %s\n' % str(err))
            return 1

    def _call_pref_dialog(self):
        d = MyDialog(self._master, self._config)
        print d._config
        self._config['cheating_percentage'] = d._config['cheating_percentage']
        self._config['cheating'] = d._config['cheating']
        self._write_config()
        self._load_config()

    def one(self, master):
        tkMessageBox.showinfo("one", "this first.......")
        self.top = Toplevel(master=master)
        Label(self.top, text="Name: ").pack()
        e1 = Entry(self.top)
        e1.pack()
#        b1 = Button(self.top, text="  Ok  ", command=self.ok)
#        b1.pack()
        e1.focus_set()

if __name__ == "__main__":
    root = Tk()
    w = Dicey(root)
    root.mainloop()
